package fuzion24.device.vulnerability.vulnerabilities;

import com.nowsecure.android.vts.BuildConfig;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import fuzion24.device.vulnerability.test.VulnerabilityTestResult;
import fuzion24.device.vulnerability.util.DeviceInfo;

/**
 * Created by fuzion24 on 11/25/15.
 */
public class VulnerabilityResultSerialzier {

    private VulnerabilityResultSerialzier() {
    }

    public static JSONObject serializeResultsToJson(List<VulnerabilityTestResult> results, DeviceInfo devInfo) throws JSONException {
        // not sure if this is too intense to do on the main thread...
        JSONArray testResults = new JSONArray();
        JSONObject buildInfo = new JSONObject();
        JSONObject combinedResults = new JSONObject();

        buildInfo.put("fingerprint", devInfo.getBuildFingerPrint());
        buildInfo.put("kernelVersion", devInfo.getKernelVersion());
        buildInfo.put("brand", devInfo.getBuildBrand());
        buildInfo.put("manufacturer", devInfo.getBuildManufacturer());
        buildInfo.put("model", devInfo.getBuildModel());
        buildInfo.put("release", devInfo.getBuildRelease());
        buildInfo.put("sdk", devInfo.getBuildSDK());
        buildInfo.put("builddate", devInfo.getBuildDateUTC());
        buildInfo.put("id", devInfo.getBuildID());
        buildInfo.put("cpuABI", devInfo.getBuildCpuABI());
        buildInfo.put("cpuABI2", devInfo.getBuildCpuABI2());

        JSONArray supportedABIs = new JSONArray();
        for(String abi :  devInfo.getSupportedABIS()){
            supportedABIs.put(abi);
        }

        buildInfo.put("supportedABIs", supportedABIs);
        buildInfo.put("versionCode", BuildConfig.VERSION_CODE);
        buildInfo.put("versionName", BuildConfig.VERSION_NAME);

        for (VulnerabilityTestResult s : results) {
            JSONObject res = new JSONObject();
            res.put("name", s.getCVEorID());
            res.put("isVulnerable", s.isVulnerable());
            res.put("exception", s.getException());
            testResults.put(res);
        }

        combinedResults.put("buildInfo", buildInfo);
        combinedResults.put("results", testResults);

        return combinedResults;
    }

}
